<template>
	<view class="home">
		<!-- 表单区 -->
		<view class="formBox">
			<form @submit="onSubmit">
				<!-- 用于包裹整个表格 便于计算表格高度-->
				<view class="questionArea">
					<!-- 学科 -->
					<view class="PickerBox border">
						<view class="pickerName">
							题目学科：
						</view>

						<view class="pickerItem">
							<view class="picker">
								<picker @change="pickerSubject" mode=selector name="subject" :value="subjectIndex"
									:range="subjectList" :range-key="'subjectName'">
									<view class="pickerShow">
										{{subjectList[subjectIndex].subjectName}}

									</view>

								</picker>
							</view>

							<view class="pickerMore">
								<u-icon name="arrow-right"></u-icon>
							</view>
						</view>
					</view>

					<!-- 章节 -->

					<view class="PickerBox border">
						<view class="pickerName">
							题目章节：
						</view>

						<view class="pickerItem">
							<view class="picker">
								<picker @change="pickerChapter" mode=selector name="chapter" :value="chapterIndex"
									:range="chapterList" :range-key="'ChapterName'">
									<view class="pickerShow">
										{{chapterList[chapterIndex].ChapterName}}

									</view>

								</picker>
							</view>

							<view class="pickerMore">
								<u-icon name="arrow-right"></u-icon>
							</view>
						</view>
					</view>

					<!-- 题目标签 -->
					<view class="tagBox">
						<!-- 项目标签标题 -->
						<view class="tagTitle">
							题目标签(选填)
						</view>

						<!-- 填写标签项 -->
						<view class="tagItem border" v-for="tagList in tagList" :key="tagList.tagId">
							<view class="tagText">
								{{tagList.tagTitle}}
							</view>

							<view class="tagInput">
								<input type="text" :name="`${tagList.tag}`" :placeholder="`${tagList.placeHolde}`"
									v-model="tagList.name">
							</view>

						</view>

						<!-- 选择题目难度 -->
						<view class="PickerBox border">
							<view class="pickerName">
								题目难度：
							</view>

							<view class="pickerItem">
								<view class="picker">
									<picker @change="pickerDifficulty" mode=selector name="tagDifficulty"
										:value="difficultyIndex" :range="difficultyList" :range-key="'name'">
										<view class="pickerShow">
											{{difficultyList[difficultyIndex].name}}

										</view>

									</picker>
								</view>

								<view class="pickerMore">
									<u-icon name="arrow-right"></u-icon>
								</view>
							</view>
						</view>

					</view>

					<!-- 题目标题内容 -->
					<view class="questionTitleBox border">
						<view class="questionTitleName">
							内容:
						</view>

						<!-- 用多行输入框输入的题目标题内容 -->
						<view class="questionTitle">
							<textarea name="questionTitle" placeholder="请输入题目内容" v-model="dataList[0].questionTitle"
								maxlength="200"></textarea>
						</view>

					</view>

					<!-- 选项标题区 -->
					<view class="option">
						题目选项
					</view>

					<!-- 选项输入区 -->
					<!-- A -->
					<view class="optionBox border">
						<!-- 选项名称 -->
						<view class="optionName">
							A:
						</view>

						<!-- 选项内容 -->
						<view class="optionContent">
							<input type="text" name="optionContentA" v-model="dataList[0].optionContentA">
						</view>
					</view>
					<!-- B -->
					<view class="optionBox border">
						<!-- 选项名称 -->
						<view class="optionName">
							B:
						</view>

						<!-- 选项内容 -->
						<view class="optionContent">
							<input type="text" name="optionContentB" v-model="dataList[0].optionContentB">
						</view>
					</view>

					<!-- C -->
					<view class="optionBox border">
						<!-- 选项名称 -->
						<view class="optionName">
							C:
						</view>

						<!-- 选项内容 -->
						<view class="optionContent">
							<input type="text" name="optionContentC" v-model="dataList[0].optionContentC">
						</view>
					</view>
					<!-- D -->
					<view class="optionBox border">
						<!-- 选项名称 -->
						<view class="optionName">
							D:
						</view>

						<!-- 选项内容 -->
						<view class="optionContent">
							<input type="text" name="optionContentD" v-model="dataList[0].optionContentD">
						</view>
					</view>

					<!-- 正确选项 -->
					<view class="answerBox border">
						<view class="answername">
							正确选项:
						</view>

						<view class="answerpicker">
							<picker @change="bindPickerChange" mode=selector name="answer" :value="pickerIndex"
								:range="optionList">
								<!-- 显示选择的正确选项 -->
								<view class="pickerShow">
									{{optionList[pickerIndex]}}
								</view>

							</picker>
							<!-- 更多图标 -->
							<view class="pickerMore">
								<u-icon name="arrow-right"></u-icon>
							</view>
						</view>


					</view>

					<!-- 解析 -->
					<view class="questionTitleBox border">
						<view class="questionTitleName">
							解析：
						</view>

						<!-- 用多行输入框输入的题目解析内容 -->
						<view class="questionTitle">
							<textarea name="analysis" v-model="dataList[0].analysis" placeholder="请输入题目解析"
								maxlength="500"></textarea>
						</view>

					</view>
				</view>

				<!-- 按钮 -->
				<!-- 用submit事务记得带上form-type，不然没有效果 -->
				<view class="itemButton">
					<button form-type="submit" type="primary" :disabled="inDisable(dataList)">提交</button>
				</view>
			</form>
		</view>

	</view>
</template>

<script>
	const db = uniCloud.database();
	const dbCmd = db.command ;
	export default {
		data() {
			return {
				uid:"",//用户id
				qid:"",//记录当前题目id
				mode:"",//当前是否以编辑模式进入
				chapterIndex: 0, //用于记录章节选择,
				chapterList: [], //用于保存章节数据
				subjectIndex: 0, //记录学科数组下标
				subjectList: [], //用于选择学科的数组
				difficultyIndex: 0, //用于记录难度选择
				difficultyList: [ //用于保存难度数据
					{
						difficulty: 0,
						name: "基础篇"
					}, {
						difficulty: 1,
						name: "提高篇"
					}
				],
				pickerIndex: 0, //记录正确选项数组下标
				pickerData: "", //记录正确选项是ABCD的哪一个
				optionList: ["A", "B", "C", "D"],
				// 提交后保存添加的题目
				dataList: [{
					subjectId: 0, //学科类别（cid）
					chapterId: 0, //章节id（ChapterId）
					questionTitle: "", //题目标题内容
					optionContentA: "", //选项A内容
					optionContentB: "", //选项B内容
					optionContentC: "", //选项C内容
					optionContentD: "", //选项D内容
					answer: "", //记录正确答案
					analysis: "", //解析,
					tagDifficulty: 0, //题目难度，0代表基础，1代表提高
					tagSource: "", //题目来源
					tagSection: "" //题目的篇章名称

				}],
				tagList: [ //用于遍历题目标签标题
					{
						tagId: 0,
						tagTitle: "题目章节名称:",
						placeHolde: "请填写题目的章节名称",
						name: "",
						tag: "tagSection"
					},
					{
						tagId: 1,
						tagTitle: "题目来源:",
						placeHolde: "请填写题目来源",
						name: "",
						tag: "tagSource"
					}
				]



			};
		},
		onUnload() {
			// if(this.mode == "edit"){
			// 	uni.redirectTo({
			// 		url:""
			// 	})
				
			// }
			 var pages = getCurrentPages(); //当前页面栈
			         if (pages.length > 1) {
			           var beforePage = pages[pages.length - 2]; //获取上一个页面实例对象
			           beforePage.data.backRefresh = true;
					   beforePage.data.chapterId = this.chapterIndex;
					   beforePage.data.cid =this.subjectIndex;
					   beforePage.data.uid =this.uid;
					   beforePage.data.mode = "nomal";
			         }
		},
		onReady() {
			
		},
		onLoad(e) {
			this.getSubjectData();
			
			if(e.mode == "edit"){
				console.log("e",e);
				this.dsEdit(e);
				this.mode = e.mode;
				this.uid = e.uid;
			}
		},
		methods: {
			//修改题目
			async dsEdit(e){
				// this.dataList[0].subjectId = parseInt(e.cid) ;
				// this.dataList[0].chapterId = parseInt(e.chapterId);
				this.chapterIndex = parseInt(e.chapterId);
				this.subjectIndex = parseInt(e.cid) ;
				console.log("this.chapterIndex",this.chapterIndex);
				console.log("this.chapterIndextyY",typeof(this.chapterIndex));
				console.log("this.subjectIndex",this.subjectIndex);
				console.log("this.subjectIndextyY",typeof(this.subjectIndex) );
				db.collection("ds").where({
					_id:e.qid
				}).get()
				.then(res=>{
					const questionObj = res.result.data[0];
					console.log("res",questionObj);
					this.qid = questionObj._id;
					this.dataList[0].questionTitle = questionObj.questionContent;
					this.dataList[0].optionContentA = questionObj.AoptionContent;
					this.dataList[0].optionContentB = questionObj.BoptionContent;
					this.dataList[0].optionContentC = questionObj.CoptionContent;
					this.dataList[0].optionContentD = questionObj.DoptionContent;
					this.difficultyIndex = questionObj.tagDifficulty;
					this.dataList[0].answer = questionObj.answer;
					this.dataList[0].analysis = questionObj.analysisContent;
					this.dataList[0].tagSource = questionObj.tagSource;
					this.dataList[0].tagSection = questionObj.tagSection;
					console.log("this.dataList[0]",this.dataList[0]);
					// 将对应的选项转成数字
					if(this.dataList[0].answer == "A"){
						this.pickerIndex = 0;
					}else if(this.dataList[0].answer == "B"){
						this.pickerIndex = 1;
					}else if(this.dataList[0].answer == "C"){
						this.pickerIndex = 2;
					}else if(this.dataList[0].answer == "D"){
						this.pickerIndex = 3;
					}
					//将标签转导入tagList
					this.tagList[0].name = this.dataList[0].tagSection;
					this.tagList[1].name = this.dataList[0].tagSource;
					console.log("tagList",this.tagList);
				})
			},
			
			//提交表单
			onSubmit(e) {
				console.log("e1",e);
				//将e.detail.value.chapter转为int类型
				e.detail.value.chapter = parseInt(e.detail.value.chapter);
				//将e.detail.value.answer中数字转成对应的选项
				if (e.detail.value.answer == "0") {
					e.detail.value.answer = "A"
				} else if (e.detail.value.answer == "1") {
					e.detail.value.answer = "B"
				} else if (e.detail.value.answer == "2") {
					e.detail.value.answer = "C"
				} else if (e.detail.value.answer == "3") {
					e.detail.value.answer = "D"
				}
				if(this.mode == "edit"){
					this.updataQuetion(e);
				}else{
					this.addQuetion(e);
				}
				
			},
			//修改题目
			async updataQuetion(e){
				const quetionObj = e.detail.value;
				console.log("editty",typeof(quetionObj.subject));
				console.log("edit",quetionObj.subject);
				const updataMeg = db.collection('ds').where({
					_id:this.qid
				})
				.update({
					Cid: parseInt(quetionObj.subject) ,
					Chapterid: parseInt(quetionObj.chapter) ,
					questionContent: quetionObj.questionTitle,
					AoptionContent: quetionObj.optionContentA,
					BoptionContent: quetionObj.optionContentB,
					CoptionContent: quetionObj.optionContentC,
					DoptionContent: quetionObj.optionContentD,
					answer: quetionObj.answer,
					analysisContent: quetionObj.analysis,
					tagDifficulty: quetionObj.tagDifficulty,
					tagSource: quetionObj.tagSource,
					tagSection: quetionObj.tagSection,
				})
				
				updataMeg.then(res=>{
					console.log("updata",res);
					uni.showToast({
						title: "修改成功~"
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 900)
				})
			},

			//将信息添加到数据库
			async addQuetion(e) {
				const quetionObj = e.detail.value;
				this.decideNull(quetionObj);
				console.log("quetionObj", quetionObj);
				const addMeg = await db.collection("ds").add({
					Cid: quetionObj.subject,
					Chapterid: quetionObj.chapter,
					questionContent: quetionObj.questionTitle,
					AoptionContent: quetionObj.optionContentA,
					BoptionContent: quetionObj.optionContentB,
					CoptionContent: quetionObj.optionContentC,
					DoptionContent: quetionObj.optionContentD,
					answer: quetionObj.answer,
					analysisContent: quetionObj.analysis,
					tagDifficulty: quetionObj.tagDifficulty,
					tagSource: quetionObj.tagSource,
					tagSection: quetionObj.tagSection,
				});
				console.log("addmeg",addMeg);
				// const Qnum = this.getQnum() ;
				// let Qnum = toString(this.getQnum()) ;
				const qid = addMeg.result.id;
				this.getQnum(qid,quetionObj.subject,quetionObj.chapter);
				// console.log("add里",this.getQnum());
				
			},
			//判断提交表格是否为空
			decideNull(quetionObj){
				if(quetionObj.questionTitle == ""){
					uni.showToast({
						title:"题目内容不能为空",
						icon:'none'
					})
				}else if(quetionObj.optionContentA == "" || quetionObj.optionContentB== ""||quetionObj.optionContentC== ""||quetionObj.optionContentD== "" ){
						uni.showToast({
							title:"题目选项不能为空",
							icon:'none'
						})
				}else if(quetionObj.analysis == ""){
					uni.showToast({
						title:"题目解析不能为空",
						icon:'none'
					})
				}
			},
			
			
			//获取新增题目的题号
			async getQnum(qid ,subjectId,chapterId){
				console.log("subjectId",subjectId);
				console.log("chapterId",chapterId);
				const QnumList = await db.collection("ds").where({
					Cid:subjectId,
					Chapterid:chapterId
				}).field("_id").get();
				console.log("QnumList",QnumList);
				
				const Qnum = QnumList.result.data.length ;
				console.log("Qnum", typeof(Qnum) );
				console.log("add里", Qnum );
				// return Qnum;
				db.collection("ds").where({
					_id:qid
				})
				.update({
					name:Qnum
				}).then(res => {
					uni.showToast({
						title: "添加成功~"
					})
					setTimeout(() => {
						uni.reLaunch({
							url: "/pages/self/self"
						})
					}, 900)
				})
			},
			
			//将题号更新到题目的name里
			// addQnum(qid){
			// 	;
			// }
			
			//获取学科分类数据
			getSubjectData() {
				db.collection("subject_classification").get().then(res => {
					this.getChapterData();
					console.log("subjectData", res);
					this.subjectList = res.result.data
				}).catch(() => {
					uni.showToast({
						title: "学科分类数据获取失败",
						icon: 'error'
					})
				})
			},

			//获取学科选择分类后的章节
			getChapterData() {
				console.log("subjectIndex", this.subjectIndex);
				db.collection("chapter").where({
						cid: this.subjectIndex
					})
					.orderBy(
						"Chapterid", "asc"
					).get().then(res => {
						this.chapterList = res.result.data;
						console.log("chapterList", this.chapterList);
					}).catch(() => {
						uni.showToast({
							title: "章节数据获取失败",
							icon: 'error'
							})
				})
			},

			//改变学科选择
			pickerSubject(e) {

				this.subjectIndex = parseInt(e.detail.value);
				this.dataList.subjectId = parseInt(this.subjectList[this.subjectIndex].cid);
				this.getChapterData();
				this.chapterIndex = 0;
				// console.log("this.dataList.subjectId",this.dataList.subjectId);
			},

			//改变章节选择
			pickerChapter(e) {
				this.chapterIndex = parseInt(e.detail.value);
				this.dataList.chapterId = parseInt(this.chapterList.cid);
			},
			//改变题目难度
			pickerDifficulty(e) {
				this.difficultyIndex = parseInt(e.detail.value);
				this.dataList.tagDifficulty = parseInt(this.difficultyIndex);
				console.log("e", this.dataList.tagDifficulty);
			},

			//记录正确选项
			bindPickerChange(e) {
				// console.log('picker发送选择改变，携带值为', e.detail.value)
				this.pickerIndex = e.detail.value;
				this.pickerData = this.optionList[this.pickerIndex];
				this.dataList.answer = this.optionList[this.pickerIndex];
				console.log("answer", this.dataList.answer);

			},

			//判断新增输入文章是否为空
			inDisable(obj) {
				for (let key in obj) {
					if (key == "") {
						return true;
					}
				}
			},




		}
	}
</script>

<style lang="scss">
	$textSize:28rpx;

	view {
		box-sizing: border-box;
	}

	page {
		background-color: #f8f8f8;
		position: relative;
	}

	.border {
		position: relative;
	}

	.border::after {
		border-bottom: 1px solid #eee;
		bottom: 0;
		box-sizing: border-box;
		content: " ";
		left: 12rpx;
		pointer-events: none;
		position: absolute;
		right: 12rpx;
		transform: scaleY(.5);
		transform-origin: center;
	}

	.formBox {
		background-color: #ffffff;
	}
	.questionArea{
		overflow-y:scroll;
		height: calc(100vh - 150rpx);
	}
	
	
	.questionTitleBox {
		display: flex;
		padding: 18rpx 12rpx;

		// justify-content: space-between;
		.questionTitleName {
			font-size: $textSize;
		}

		.questionTitle {
			padding-left: 8rpx;
			border-radius: 16rpx;
			border: 1rpx solid #eee;
			align-items: top;
		}
	}

	.option {
		font-size: $textSize;
		font-weight: bold;
		padding: 12rpx;
	}

	.optionBox {
		display: flex;
		align-items: center;
		padding: 12rpx 32rpx;

		.optionName {
			padding-right: 12rpx;
			font-size: $textSize;
		}

		.optionContent {
			width: 85%;
			border-radius: 16rpx;
			border: 1rpx solid #eee;
		}
	}

	.answerBox {
		padding: 20rpx 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: $textSize;

		.answerpicker {
			// width: 40%;
			display: flex;
			align-items: center;

			.pickerShow {
				text-align: right;

			}
		}
	}

	.PickerBox {
		padding: 18rpx 12rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.pickerName {
			font-size: $textSize;
		}

		.pickerItem {
			display: flex;
			justify-content: flex-end;
			align-items: center;

			.pickerShow {
				text-align: right;
			}
		}
	}

	.itemButton {
		background-color: #ffffff;
		padding: 18rpx 18rpx 50rpx 18rpx;
		width: 100%;
		position: fixed;
		bottom: 0;
	}

	.tagBox {
		padding: 12rpx;

		.tagTitle {
			font-size: 32rpx;
			font-weight: bold;
		}

		.tagItem {
			padding: 12rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.tagText {
				font-size: $textSize;
			}

			.tagInput {
				border: 1rpx solid #eee;
				border-radius: 16rpx;
				width: 70%;
			}
		}

	}
</style>
